package com.xiaxiang.xiawan.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;

import com.dg.acb.utils.configdata.DGConfigData;
import com.dg.acb.utils.configdata.XXConstants;
import com.dg.acb.utils.configdata.XXUserInfoData;
import com.donggua.aichebao.login.DGLoginCommonBase;
import com.donggua.aichebao.login.DGThirdLogin;
import com.third.login.ThirdLoginData;
import com.third.login.ThirdLoginPlatform;
import com.xiaxiang.xiawan.R;
import com.xiaxiang.xiawan.XXConfigData;
import com.xiaxiang.xiawan.XXMainApplication;
import com.xx.xiawan.net.DGJsonRequest;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by fzh on 2017/8/4.
 */

public class XXClientLogin extends DGLoginCommonBase {
    protected ViewStub stubMessageLogin;
    protected ViewStub stubThirdLogin;
    protected View tvMessageLogin;
    protected View tvPasswordLogin;
    protected ImageView imgQQLogin;
    protected ImageView imgWeiXinLogin;
    protected ImageView imgSinaLogin;
    private DGConfigData mConfigData;
    private boolean mIsLoginSuccess = false;
    public final static String TOKEN_KEY = "token";
    public final static String OPEN_ID_KEY = "openId";
    public final static String CLIENT_ID_KEY = "clientId";
    public final static String CLIENT_SECRET_KEY = "clientSecret";
    public final static String USER_KEY = "user";
    public final static String ICON_URL_KEY = "iconUrl";
    public final static String TYPE_KEY = "type";
    public final static String MACHINE_ID_KEY = "machineId";
    private XXMainApplication mApp = null;
    private String mMachineId = "";
    public XXClientLogin(Activity act, View mainView) {
        super(act, mainView);
        dgThirdLogin = new DGClientThirdLogin(act);
        mConfigData = new DGConfigData(getContext());
        mApp = (XXMainApplication)act.getApplication();
        mMachineId = mApp.getMachineId();
        if(mMachineId == null || mMachineId.length() == 0){
            mMachineId = "11111111111";
        }
    }

    public Context getContext() {
        return act.getApplicationContext();
    }

    @Override
    public void onLogin() {
        /*
        Log.e("share"," startShare");
        ShareData shareData = new ShareData();
        shareData.mShareUrl =XXToolUtil.videourl;
        shareData.mThumbFileUrl = XXToolUtil.imageurl;
        shareData.mShareTitle = "xiaxiang.xiawiang.xiawan";
        shareData.mShareStyle = ShareTest.VIDEO11;
        mShareDialog.setShareData(shareData);
        mShareDialog.showDialog();
        */
        //mShareTest.startShare(ShareTest.TEXT);
      ///  dgThirdLogin.cancelLogin();
    }

    protected void init() {
        super.init();
        stubMessageLogin = (ViewStub) mainView.findViewById(com.donggua.aichebao.login.R.id.stubMessageLogin);
        stubMessageLogin.setVisibility(View.VISIBLE);
        stubThirdLogin = (ViewStub) mainView.findViewById(com.donggua.aichebao.login.R.id.stubThirdLogin);
        stubThirdLogin.setVisibility(View.VISIBLE);
        tvMessageLogin = mainView.findViewById(com.donggua.aichebao.login.R.id.tvCommonMessageLogin);
        tvPasswordLogin = mainView.findViewById(com.donggua.aichebao.login.R.id.tvCommonPasswordLogin);
        imgQQLogin = (ImageView) mainView.findViewById(com.donggua.aichebao.login.R.id.imgQQLoad);
        imgWeiXinLogin = (ImageView) mainView.findViewById(com.donggua.aichebao.login.R.id.imgWeiXinLoad);
        imgSinaLogin = (ImageView) mainView.findViewById(com.donggua.aichebao.login.R.id.imgSinaLoad);
        tvMessageLogin.setOnClickListener(this);
        tvPasswordLogin.setOnClickListener(this);
        imgQQLogin.setOnClickListener(this);
        imgWeiXinLogin.setOnClickListener(this);
        imgSinaLogin.setOnClickListener(this);
    }

    public void doOnClick(View view) {
        int id = view.getId();
        Log.e("login", " donClick id is " + id);
        imgQQLogin.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    imgQQLogin.setImageResource(R.mipmap.lg_qq1);
                }else if(event.getAction()==MotionEvent.ACTION_UP){
                    imgQQLogin.setImageResource(R.mipmap.lg_qq);
                }
                return false;
            }
        });
        imgWeiXinLogin.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    imgWeiXinLogin.setImageResource(R.mipmap.lg_wx1);
                }else if(event.getAction()==MotionEvent.ACTION_UP){
                    imgWeiXinLogin.setImageResource(R.mipmap.lg_wx);
                }
                return false;
            }
        });

        imgSinaLogin.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction()==MotionEvent.ACTION_DOWN){
                    imgSinaLogin.setImageResource(R.mipmap.lg_wb1);
                }else if(event.getAction()==MotionEvent.ACTION_UP){
                    imgSinaLogin.setImageResource(R.mipmap.lg_wb);
                }
                return false;
            }
        });

        if (id == com.donggua.aichebao.login.R.id.tvCommonMessageLogin) {
            if (MESSAGELOGIN != loginStyle) {
                loginStyle = MESSAGELOGIN;
                stubMessageLogin.setVisibility(View.VISIBLE);
                stubPasswordLogin.setVisibility(View.GONE);
            }
        } else if (id == com.donggua.aichebao.login.R.id.tvCommonPasswordLogin) {
            if (PASSWORDLOGIN != loginStyle) {
                loginStyle = PASSWORDLOGIN;
                stubMessageLogin.setVisibility(View.GONE);
                stubPasswordLogin.setVisibility(View.VISIBLE);
            }
        } else if (id == com.donggua.aichebao.login.R.id.imgQQLoad) {
            Log.e("login", " btn QQLogin");
            handleLoging(QQLOGIN);
        } else if (id == com.donggua.aichebao.login.R.id.imgSinaLoad) {
            Log.e("login", " btn SinaLoad");
            handleLoging(SINALOGIN);
        } else if (id == com.donggua.aichebao.login.R.id.imgWeiXinLoad) {
            Log.e("login", " btn WeiXinLoad");
            handleLoging(WEIXINLOGIN);
        }
    }

    private JSONObject onQQComplete(ThirdLoginPlatform platform, ThirdLoginData LoginData) {
        JSONObject object = new JSONObject();
        Map<String, String> data = LoginData.data;

        try {
            object.put(TOKEN_KEY, data.get("access_token"));
            object.put(OPEN_ID_KEY, data.get("openid"));
            object.put(CLIENT_ID_KEY, XXConstants.appKeyQQ);
            object.put(CLIENT_SECRET_KEY, XXConstants.appSecretQQ);
            object.put(USER_KEY, data.get("name"));
            object.put(ICON_URL_KEY, data.get("iconurl"));
            object.put(TYPE_KEY, platform.getPlatformStyle());
            object.put(MACHINE_ID_KEY,mMachineId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return object;
    }

    private JSONObject onWXComplete(ThirdLoginPlatform platform, ThirdLoginData LoginData) {
        JSONObject object = new JSONObject();
        Map<String, String> data = LoginData.data;

        try {
            object.put(TOKEN_KEY, data.get("access_token"));
            object.put(OPEN_ID_KEY, data.get("openid"));
            object.put(CLIENT_ID_KEY, XXConstants.appKeyWeiXin);
            object.put(CLIENT_SECRET_KEY, XXConstants.appSecretWeiXin);
            object.put(USER_KEY, data.get("screen_name"));
            object.put(ICON_URL_KEY, data.get("iconurl"));
            object.put(TYPE_KEY, platform.getPlatformStyle());
            object.put(MACHINE_ID_KEY,mMachineId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return object;
    }

    private JSONObject onWBComplete(ThirdLoginPlatform platform, ThirdLoginData LoginData) {
        JSONObject object = new JSONObject();
        Map<String, String> data = LoginData.data;
         /*
            public final static String TOKEN_KEY = "token";
    public final static String OPEN_ID_KEY = "openId";
    public final static String CLIENT_ID_KEY = "clientId";
    public final static String CLIENT_SECRET_KEY = "clientSecret";
    public final static String USER_KEY = "user";
    public final static String ICON_URL_KEY = "iconUrl";
    public final static String TYPE_KEY = "type";
    public final static String MACHINE_ID_KEY = "mechineid";
         */
        try {
            object.put(TOKEN_KEY, data.get("access_token"));
            object.put(OPEN_ID_KEY, data.get("openid"));
            object.put(CLIENT_ID_KEY, XXConstants.appKeySinaWeibo);
            object.put(CLIENT_SECRET_KEY, XXConstants.appSecretSinaWeibo);
            object.put(USER_KEY, data.get("name"));
            object.put(ICON_URL_KEY, data.get("iconurl"));
            object.put(TYPE_KEY, platform.getPlatformStyle());
            object.put(MACHINE_ID_KEY,mMachineId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }


    private class DGClientThirdLogin extends DGThirdLogin {

        public DGClientThirdLogin(Activity activity) {
            super(activity);
        }

        @Override
        public void onStart(ThirdLoginPlatform platform) {
        }

        @Override
        public void onComplete(final ThirdLoginPlatform platform, final int action, final ThirdLoginData data) {
            Log.i("drj", "platform" + platform);
            Log.i("drj", "action" + action);
            JSONObject object = null;
            switch (platform) {
                case QQ:
                    object = onQQComplete(platform, data);
                    break;

                case WEIXIN:
                    object = onWXComplete(platform, data);
                    break;

                case SINA:
                    object = onWBComplete(platform, data);
                    break;

                default:
                    break;
            }

            Log.e("login", " qq object is " + object);
           // String url = "http://192.168.8.101:8089/v1/login/oauth2Login";
            String url = XXConstants.URI_OAUTH_2_LOGIN;
            final JSONObject finalObject = object;
            DGRequestListener listener = new DGRequestListener(){

                @Override
                public void onSuccess(DGJsonResult result) {
                    Log.e("login", "jsonObject is " + result.result);
                    if (result.errorCode == 0) {
                        try {
                            JSONObject resObject = new JSONObject(result.result);
                            mIsLoginSuccess= resObject.getBoolean("isLogin");
                            if (mIsLoginSuccess) {
                                /*
                                String token = resObject.getString("token");
                                Log.i("drj", "login; " + "token: " + token);
                                Intent intent = new Intent();
                                intent.setClass(act, MainActivity.class);
                                act.startActivity(intent);
                                act.finish();
                                */
                                Intent intent = new Intent();
                                intent.putExtra("loginData",resObject.toString());
                                act.setResult(XXConfigData.LOGIN_RECODE_SUCCESS,intent);
                                XXMainApplication application = (XXMainApplication)act.getApplication();

                                boolean mIsLogin = true;
                                String mUser = resObject.getString("userName");
                                String mToken = resObject.getString(TOKEN_KEY);
                                String mHeadUrl = resObject.getString("headPhoto");
                                XXUserInfoData userInfoData = new XXUserInfoData(mIsLogin,mUser,mToken,mHeadUrl);
                                application.setUserInfo(userInfoData);
                                act.finish();
                            } else {
                                setResultError();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(String error) {
                    setResultError();
                }
            };
            DGJsonRequest jsonLoginRequest = new DGJsonRequest(act,url,object,listener);
            jsonLoginRequest.startNoLock();
        }

        @Override
        public void onError(ThirdLoginPlatform platform, int action, String errorMsg, Throwable t) {
            setResultError();
        }

        @Override
        public void onCancel(ThirdLoginPlatform platform, int action) {
           // setResultError();
        }
    }

    private void setResultError(){
        act.setResult(XXConfigData.LOGIN_RECODE_FAIL);
        act.finish();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
     //   mShareTest.onDestroy();
        if(mIsLoginSuccess){

        }else{
           // setResultError();
            act.setResult(XXConfigData.LOGIN_RECODE_FAIL);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
      //  mShareTest.onActivityResult(requestCode,resultCode,data);
    }
}
